package com.quick.develop.flowable.framework.core;

import com.quick.develop.flowable.framework.factory.FlowServiceFactory;
import com.quick.develop.flowable.service.task.IBpmCommentService;
import lombok.extern.slf4j.Slf4j;
import org.flowable.common.engine.api.delegate.event.FlowableEvent;
import org.flowable.common.engine.api.delegate.event.FlowableEventListener;
import org.flowable.engine.delegate.event.impl.FlowableEntityEventImpl;
import org.flowable.engine.task.Event;
import org.flowable.task.service.impl.persistence.entity.TaskEntityImpl;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * desc: 任务结束全局监听
 *
 * @author junyuan.liu
 * @date 2023/2/27 13:08
 */
@Component
@Slf4j
public class BpmTaskCompletedListener extends FlowServiceFactory implements FlowableEventListener {

    @Resource
    private IBpmCommentService commentService;

    @Override
    public void onEvent(FlowableEvent flowableEvent) {
        System.out.println("=====BpmTaskCompletedListener===");
        TaskEntityImpl entity = (TaskEntityImpl) ((FlowableEntityEventImpl) flowableEvent).getEntity();
        String taskId = entity.getId();
        String fullMessage = null;
        List<Event> comments = commentService.getTaskEvents(taskId).stream().filter(event -> Objects.equals(event.getAction(),Event.ACTION_ADD_COMMENT)).collect(Collectors.toList());
        if (comments.size() == 1){
             fullMessage = comments.get(0).getMessage();
        }
        if(comments.size() > 1){
            fullMessage = comments.stream().map(Event::getMessage).collect(Collectors.joining(""));
        }
    }

    @Override
    public boolean isFailOnException() {
        return true;
    }

    @Override
    public boolean isFireOnTransactionLifecycleEvent() {
        return false;
    }

    @Override
    public String getOnTransaction() {
        return null;
    }
}
